import requests
import json

# 定义 API 的 URL
url = 'https://open.hunyuan.tencent.com/openapi/v1/agent/chat/completions'

# 定义请求头
headers = {
    'X-Source': 'openapi',
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <token>'  # 替换为您的实际token
}

# 定义请求体
data = {
    "assistant_id": "",  # 替换为您的实际助手ID
    "user_id": "",  # 替换为实际的用户ID
    "stream": True,  # 是否以流式接口的形式返回数据
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "你好呀"
                }
            ]
        }
    ]
}

# 发送 POST 请求
response = requests.post(url, headers=headers, json=data, stream=True)

# 检查响应状态码
if response.status_code != 200:
    print(f"请求失败，状态码: {response.status_code}")
    print(response.text)
else:
    # 处理流式返回
    for line in response.iter_lines():
        if line:
            line_str = line.decode('utf-8')
            if line_str.startswith('data: '):
                # 去掉前缀 'data: '
                json_str = line_str[len('data: '):]
                if json_str == '[DONE]':
                    break
                else:
                    try:
                        # 尝试解析JSON
                        json_data = json.loads(json_str)
                        print(json_data['choices'][0]['delta']['content'], end='')
                    except json.JSONDecodeError as e:
                        # 如果解析失败，打印错误信息
                        print(f"JSON解析错误: {e}")
                        print(f"原始行数据: {line_str}")
